package one.stand.controller;

import com.alibaba.fastjson.JSON;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import one.stand.model.ResultModel;
import one.stand.request.ComponentProgramRequest;
import one.stand.request.ComponentVerifyTicketRequest;
import one.stand.request.wx.*;
import one.stand.response.wx.AuthSnsapiUserinfoResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.util.Map;

/**
 * @author: QIK
 * @CreateDate: 2019/5/9 14:33
 */
@RestController
@RequestMapping("wechatApi/wx")
@Slf4j
public class WxController extends BaseController {

    @RequestMapping("wxcallback/{appid}")
    public String wxcallback(@PathVariable("appid") String appid, HttpServletRequest httpServletRequest, ComponentVerifyTicketRequest request) {
        Map<String, String[]> data = httpServletRequest.getParameterMap();
        logger.info("回调参数ticket:{}", JSON.toJSONString(data));
        StringBuffer inputString = new StringBuffer();
        try {
            BufferedReader reader = httpServletRequest.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            httpServletRequest.getReader().close();
            logger.info("微信回调流ticket：{}", inputString.toString());
        } catch (Exception e) {
            log.error("回调参数ticket[异常]", e);
        }
        request.setAppid(appid);
        request.setXml(inputString.toString());
        return wechatFegin.wxcallback(request);
    }

    @RequestMapping("program/{appid}")
    public String program(@PathVariable("appid") String appid, HttpServletRequest httpServletRequest, ComponentProgramRequest request) {
        Map<String, String[]> data = httpServletRequest.getParameterMap();
        logger.info("回调参数program:{}", JSON.toJSONString(data));
        StringBuffer inputString = new StringBuffer();
        try {
            BufferedReader reader = httpServletRequest.getReader();
            String line;
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            httpServletRequest.getReader().close();
            logger.info("微信回调流program：{}", inputString.toString());
        } catch (Exception e) {
            log.error("微信回调流program[异常]", e);
        }
        request.setAppid(appid);
        request.setXml(inputString.toString());
        return wechatFegin.program(request);
    }

    @GetMapping("subscribe-templates")
    public ResultModel subscribeTemplates(HttpServletRequest request) {
        String companyKey = request.getHeader("companyKey");
        if (StringUtils.isEmpty(companyKey)) {
            companyKey = request.getHeader("company_key");
        }
        String accountType = request.getParameter("accountType");
        return wechatFegin.subscribeTemplates(companyKey, accountType);
    }

    /**
     * 微信公众号 auth2.0
     * @param request
     * @return
     */
    @ApiOperation("参数code=weixincode ,state=appid+文章id")
    @GetMapping("wxAuth")
    public RedirectView wxAuth(HttpServletRequest request , HttpServletResponse response) {
        log.info("wechatCallback:{}",request.getParameter("code"));
        AuthSnsapiUserinfoResponse result = wechatFegin.wxAuth(request.getParameter("code"),request.getParameter("state"));
        if(result != null && result.getUrl() != null){
            log.info("RedirectView:{}",result.getUrl());
            return  new RedirectView(result.getUrl());
        }
        //todo 默认地址
        return  new RedirectView("未知错误!");
    }

    /**
     * 微信公众号 绑定认证
     * @param appid
     * @param request
     * @return
     */
    @RequestMapping(path = "msg/{appid}",produces = "text/plain;charset=utf-8")
    public String authGet(@PathVariable String appid,WxAuthRequest request ){
        request.setAppid(appid);
        log.info("WxAuthRequest:{}",request);
        return wechatFegin.authGet(request);
    }

    /**
     * 接受微信客服消息
     * @param appid
     * @param requestBody
     * @param request
     * @param encType
     * @param msgSignature
     * @return
     */
    @PostMapping(path = "msg/{appid}")
    public String post(@PathVariable String appid,@RequestBody String requestBody,WxMsgRequest request,  @RequestParam(name = "encrypt_type", required = false) String encType,
                       @RequestParam(name = "msg_signature", required = false) String msgSignature) {
        request.setRequestBody(requestBody);
        request.setEncType(encType);
        request.setMsgSignature(msgSignature);
        request.setAppid(appid);
        log.info("WxMsgRequest:{}",request);
        return wechatFegin.post(request);
    }

    /**
     * 获取jssdk签名
     * @param request
     * @return
     */
    @PostMapping("getWxJsapiSignature")
    public ResultModel getWxJsapiSignature(@RequestBody WxMsgRequest request){
        return wechatFegin.getWxJsapiSignature(request);
    }

    @PostMapping("refreshSubscribeTemplates")
    public ResultModel refreshSubscribeTemplates(@RequestBody WxMsgRequest request) {
        return wechatFegin.refreshSubscribeTemplates(request);
    }

    @PostMapping("updateShareNum")
    public String updateShareNum(@RequestBody ShareDynamicRequest request){
        return wechatFegin.updateShareNum(request);
    }

    @PostMapping("userOpenDynamic")
    public String userOpenDynamic(@RequestBody UserTimerModel request){
        return wechatFegin.userOpenDynamic(request);
    }

}
